package com.codedef.service;

import com.alibaba.fastjson.JSONObject;
import com.codedef.common.exception.CustomException;
import com.codedef.common.response.ResultCode;
import com.codedef.entity.JwtParam;
import com.codedef.entity.MqSeatBo;
import com.codedef.entity.ReservationRecord;
import com.codedef.entity.Seat;
import com.codedef.fservice.BloomCacheService;
import com.codedef.fservice.ReservationRecordService;
import com.codedef.fservice.SeatService;
import com.codedef.util.DateUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Base64;
import java.util.Date;

/**
 * @author 孙宏宇
 * @date 2021/2/24 09:35
 */
@Service
public class SignInService {

    @Autowired
    JwtParam jwtParam;

    @Autowired
    SeatService seatService;

    @Autowired
    ReservationRecordService reservationRecordService;

    @Autowired
    BloomCacheService bloomCacheService;

    @Autowired
    RabbitTemplate rabbitTemplate;


    public ReservationRecord scanQRCodeSignIn(String base, Integer userId) {
        // 从将Base64编码转换为JSON字符串, 再从中取出seatId与uuid
        JSONObject jsonObject = JSONObject.parseObject(new String(Base64.getDecoder().decode(base)));
        Integer seatId = jsonObject.getInteger("seatId");
        String uuid = jsonObject.getString("code");

        // 验证seatid与uuid是否匹配, 匹配则签到
        Seat seat = seatService.getSeatByIdFeign(seatId);
        if (seat == null || !seat.getUuid().equals(uuid))
            throw new CustomException(ResultCode.CURRENTLY_NO_RESERVATION_TO_SIGN_IN);

        // 记录签到
        // 1. 查出预约记录   当前时间 IN start_time-15, start_time+15 AND userId = {} AND state = 已预约未签到   查不到: 无预约信息, 已签到
        ReservationRecord record = reservationRecordService.getCanSignInReservationRecordFeign(seat.getId(), userId);
        if (record == null)  // 查不到则抛出异常
            throw new CustomException(ResultCode.CURRENTLY_NO_RESERVATION_TO_SIGN_IN);
        return record;
    }


    public boolean qrCodeSignIn(String base, Integer userId) {
        // 从Token的载荷获取UserId
//        Claims claims = JwtUtils.parseToken(authorization.substring(7), jwtParam.getBase64Secret());
//        int userId = (int) claims.get("id");

        // 从将Base64编码转换为JSON字符串, 再从中取出seatId与uuid
        JSONObject jsonObject = JSONObject.parseObject(new String(Base64.getDecoder().decode(base)));
        Integer seatId = jsonObject.getInteger("seatId");
        String uuid = jsonObject.getString("code");

        // 验证seatid与uuid是否匹配, 匹配则签到
        Seat seat = seatService.getSeatByIdFeign(seatId);
        if (seat == null || !seat.getUuid().equals(uuid))
            throw new CustomException(ResultCode.DATA_IS_WRONG);

        // 记录签到
        // 1. 查出预约记录   当前时间 IN start_time-15, start_time+15 AND userId = {} AND state = 已预约未签到   查不到: 无预约信息, 已签到
        ReservationRecord record = reservationRecordService.getCanSignInReservationRecordFeign(seat.getId(), userId);
        if (record == null)  // 查不到则抛出异常
            throw new CustomException(ResultCode.CURRENTLY_NO_RESERVATION_TO_SIGN_IN);
        // 2. 更改其state字段
        // 座位所属的教室Abbreviation
        String abbreviation = seatService.getClassroomAbbreviationBySeatIdFeign(record.getSeatId());
        bloomCacheService.setSeatStateFeign(abbreviation, record.getSeatId(), 10);
        reservationRecordService.updateReservationStateByIdFeign(record.getId(), 10);
        // 3. 发送RabbitMQ延时消息
        // 构建BO
        MqSeatBo mqSeatBo = new MqSeatBo(record.getId(), record.getSeatId(), userId, abbreviation);
        this.rabbitTemplate.convertAndSend("codedef.delayed", "use_que", mqSeatBo, message -> {
            message.getMessageProperties().setDelay(
                    (int) DateUtil.subtractTwoDate(record.getEndTime(), new Date())
            );
            return message;
        });
        return true;
    }

}
